import { isNavigationFailure, Router } from "vue-router";
import NProgress from "nprogress"; // progress bar
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { storage } from "@/utils/Storage";
import { useUserStore } from "@/store/modules/user";
NProgress.configure({ showSpinner: false }); // NProgress Configuration

const allowList = [
  "login",
  "error",
  "error-404",
  "components",
  "forms",
  "tables",
]; // no redirect whitelist
const loginRoutePath = "/login";
const defaultRoutePath = "/";
const isIn = (path) => {
  let flag = false;
  allowList.find((item) => {
    if (path.indexOf(item) > -1) {
      flag = true;
    }
  });
  return flag;
};

export function createRouterGuards(router: Router) {
  let flag = 0;
  router.beforeEach((to, from, next) => {
    NProgress.start(); // start progress bar
    const token = storage.getToken();
    const userStore = useUserStore();
    if (flag == 0) {
      userStore.getUserInfo();
      if (userStore.addRoutes) router.addRoute(userStore.addRoutes);
      flag++;
      next({
        ...to,
        replace: true
      })
    } else {
      next();
    }

    // if (token) {
    //   if (to.name === "Login") {
    //     next({ path: defaultRoutePath });
    //     NProgress.done();
    //   } else {
    //     if (to.name == "Layout") {
    //       next({
    //         path: "/home",
    //       });
    //     } else {
    //       next();
    //     }
    //   }
    // } else {
    //   if (isIn(to.path)) {
    //     // 在免登录名单，直接进入
    //     next();
    //   } else {
    //     next({
    //       path: loginRoutePath,
    //       query: { redirect: to.fullPath },
    //       replace: true,
    //     });
    //     NProgress.done();
    //   }
    // }
    
  });

  router.afterEach((to, from, failure) => {
    document.title = (to?.meta?.title as string) || document.title;
    NProgress.done();
  });

  router.onError((error) => {
    console.log(error, "路由错误");
  });
}
